<?php

namespace App\Service\delivery;
use App\Model\DataPaymentBackhaulError;
use App\Model\DataSpread;
use App\Model\Payment;
use App\Model\Playlet;
use App\Model\DataBackhaulSetting;
use App\Model\DataPaymentBackhaul;
use App\Model\RechargeGoods;
use App\Model\DataUserJuliangTokenRel;
use App\Service\CommicService;
use Hyperf\Paginator\Paginator;
use Hyperf\Utils\ApplicationContext;
use App\Common\Response\SystemCode;
use Hyperf\DbConnection\Db;
use GuzzleHttp\Client;
class PaymentService extends CommicService
{
    const cacheDuration = 60 * 15;

    public static $token = '7FE11418980F94B82110648EC0DAFD2B';

    public static $reportUrl = "https://clue.oceanengine.com/outer/wechat/applet/token/1779984845733000";

    public static $dyreportUrl = "https://analytics.oceanengine.com/api/v2/conversion";

    public static $starReportUrl = "https://ad.oceanengine.com/track/activate/";


    public function __construct()
    {
        $container = ApplicationContext::getContainer();
        $this->redisService = $container->get(\Hyperf\Redis\Redis::class);
        $this->userAppletIds = $this->getUserAppletInfo();
    }


    const STATUS_ENABLE  = 1;


    public function search(Array $params,$export=0){

        $keyword        = $params['keyword'] ?? ''; //短剧名称
        $pageSize       = $params['pageSize'] ?? 10;
        $page           = $params['page'] ?? 1;
        $order_id       = $params['order_id'] ?? '';//订单ID
        $ad_id          = $params['ad_id'] ?? '';//订单ID
        $is_backhaul    = $params['is_backhaul'] ?? '';//订单ID
        $user_platform  = $params['user_platform'] ?? '';//订单ID
        $user_id        = $params['user_id'] ?? '';//用户ID
        $is_first       = $params['is_first'] ?? '';//用户ID
        $transaction_id = $params['transaction_id'] ?? '';//微信交易ID
        $spread_id      = $params['spread_id'] ?? ''; //推广链接id
        $spread_name    = $params['spread_name'] ?? ''; //推广链接id
        $status         = $params['status'] ?? ''; //推广链接id
        $pay_type       = $params['pay_type'] ?? ''; //支付类型
        $goods_type       = $params['goods_type'] ?? ''; //订单类型
        $applet_ids     = $params['applet_ids'] ?? '';
        $created_at     = $params['created_at'] ?? '';
        $delivery_user_id  = $params['delivery_user_id'] ?? '';
        $amount     = $params['amount'] ?? '';
        $goods_id = '';
        if(empty($applet_ids)){
            return [];
        }
        //获取所拥有的
        if($applet_ids == '1'){
            //获取所有的小程序所绑定的短剧
            $applet_id =  $this->userAppletIds;
        }else{
            $applet_id =  [$applet_ids];
        }
        $subSelect = '';
        //2023-12-22 投放组员新增子查询
        //2023-12-11 新增可看到投放组员的数据
        if(!empty($delivery_user_id)){
//            $spreadIds = DataSpread::query()->whereIn('user_id',$delivery_user_id)->pluck('id');
            $delivery_str = implode(',',$delivery_user_id);
            $subSelect = "select `id` from `data_spread` where `user_id` in (".$delivery_str.") and `data_spread`.`deleted_at` is null";

        }else{
            $userInfo = $this->getUserAppletInfo(2);
            if($userInfo['role']['is_admin'] != 1){
                if(empty($userInfo['role']['is_check_user_order'])){
//                    $spreadIds = DataSpread::query()->where(['user_id' => $userInfo['id']])->pluck('id');
                    $subSelect = "select `id` from `data_spread` where `user_id` = ".$userInfo['id']." and `data_spread`.`deleted_at` is null";
                }
            }
        }
        $query = Payment::query()->select(['data_payment.id','data_payment.user_platform','data_payment.type','data_payment.status','data_payment.applet_id','data_payment.playlet_id','data_payment.spread_id',
            'data_payment.create_at','data_payment.transaction_id','data_payment.amount', 'data_payment.order_id','data_payment.order_time','data_payment.goods_id',
            'data_payment.pay_time','data_payment.pay_type','data_payment.ad_id','data_payment.user_id','data_payment.is_backhaul','data_payment.is_handle',
            'applet.name as applet_name','playlet.name as playlet_name','data_spread.name as spread_name','recharge_goods.name as recharge_goods_name']);
        //短剧ID
        if ($keyword) {
            $playletIds = Playlet::query()->where([['name', 'like', '%' . $keyword . '%']])->pluck('id');
        }

        if(!empty($subSelect)){
            $query->whereRaw('data_payment.spread_id in ('.$subSelect.')');
        }
        if(!empty($spreadIds)){
            $query->whereIn('data_payment.spread_id',$spreadIds);
        }
        if(!empty($playletIds)){
            $query->whereIn('data_payment.playlet_id',$playletIds);
        }
        if(!empty($created_at)){
            $created_at[0] = date('Y-m-d H:i:s',$created_at[0]/1000);
            $created_at[1] = date('Y-m-d H:i:s',$created_at[1]/1000);
            //$query->whereBetween('create_at',$created_at);
            if(!empty($created_at[0])){
                $query->where('data_payment.create_at','>',$created_at[0]);
            }
            if(!empty($created_at[1])) {
                $query->where('data_payment.create_at', '<', $created_at[1]);
            }
        }
        if(!empty($amount)){
            if(!empty($amount[0])){
                $query->where('data_payment.amount','>=',$amount[0]*100);
            }
            if(!empty($amount[1])) {
                $query->where('data_payment.amount','<=',$amount[1]*100);
            }
        }
        //用户类型
        if (!empty($user_platform)) {
            $query->Where(['data_payment.user_platform' => $user_platform]);
        }
        //订单支付类型
        if (!empty($pay_type)) {
            $query->Where(['data_payment.pay_type' => $pay_type]);
        }
        //订单状态
        if (!empty($status)) {
            $query->Where(['data_payment.status' => $status]);
        }
        //用户ID
        if (!empty($user_id)) {
            $query->Where(['data_payment.user_id' => $user_id]);
        }
        //微信交易ID
        if (!empty($transaction_id)) {
            $query->Where(['data_payment.transaction_id' => $transaction_id]);
        }
        //计划ID
        if (!empty($ad_id)) {
            $query->Where(['data_payment.ad_id' => $ad_id]);
        }
        //计划ID
        if (!empty($is_backhaul)) {
            $query->Where(['data_payment.is_backhaul' => $is_backhaul]);
        }
        //订单ID
        if (!empty($order_id)) {
            $query->Where(['data_payment.order_id' => $order_id]);
        }
        //推广ID
        if (!empty($spread_id)) {
            $query->Where(['data_payment.spread_id' => $spread_id]);
        }
        if (!empty($spread_name)) {
            $selectSpread_id = DataSpread::query()->where('name','like','%'.$spread_name.'%')->pluck('id');
            if(!empty($selectSpread_id)){
                $query->WhereIn('data_payment.spread_id', $selectSpread_id);
            }

        }
        //订单类型
        if(!empty($goods_type)){
            if(!empty(Payment::$goodsType[$goods_type])){
                //查询充值模板的goods表
                if($goods_type == 1) {
                    $subgoodsSelect = "select `id` from `recharge_goods` where `name` like '常规档位%' and `recharge_goods`.`deleted_at` is null";
                }else if($goods_type == 11){//2024-03-15 挽留充值
                    $subgoodsSelect = "select `id` from `recharge_goods` where `name` = '挽留档位' and `recharge_goods`.`deleted_at` is null";
                }else{
                    $goods_type_name = Payment::$goodsType[$goods_type];
                    $subgoodsSelect = "select `id` from `recharge_goods` where `name` = '".$goods_type_name."' and `recharge_goods`.`deleted_at` is null";
                }

                if(!empty($subgoodsSelect)){
                    $query->whereRaw('data_payment.goods_id in ('.$subgoodsSelect.')');
                }
            }
        }

        //小程序ID
        if(!empty($applet_id)){
            $query->whereIn('data_payment.applet_id',$applet_id);
        }

        if(!empty($is_first)){
            $query->where(function ($query) {
                $query->where('data_payment.first_recharge', 'Y')->orwhere('data_payment.today_first_recharge', 'Y');

            });
        }
        $countQruey = $query;
//        $total = $countQruey->select(['data_payment.id'])->count('data_payment.id');

        $models = $query
            ->leftJoin('applet','data_payment.applet_id','=','applet.id')
            ->leftJoin('playlet','data_payment.playlet_id','=','playlet.id')
            ->leftJoin('data_spread','data_payment.spread_id','=','data_spread.id')
            ->leftJoin('recharge_goods','data_payment.goods_id','=','recharge_goods.id')
            ->orderBy('id','desc')->paginate($pageSize,['*'],'page',$page);
        $items = $models->items();
        $selectData = [];
        foreach ($items as $item){
            $userIds[$item->applet_id][] = $item->user_id;
        }
        if(!empty($userIds)){
            foreach ($userIds as $applet_id => $userId){
               $userId = array_unique($userId);
               $userConut = Payment::query()->select( Db::raw("count(data_payment.`id`) as user_count"),'user_id')
                   ->where('data_payment.status',2)->where('data_payment.applet_id',$applet_id)
                   ->whereIn('user_id',$userId)->groupBy(['data_payment.user_id'])->get()->toArray();
               $userDataTime = Db::table('data_user_' . $applet_id)->select(['dyeing_time','id'])->whereIn('id',$userId)->get();
//
                if(!empty($userConut)){
                    foreach ($userConut as $val){
                        $userData[$applet_id.'_'.$val['user_id']] =  $val['user_count'];
                    }
                }
                if(!empty($userDataTime)){
                    foreach ($userDataTime as $val){
                        $userTime[$applet_id.'_'.$val->id] = $val->dyeing_time;
                    }
                }
            }
        }
        foreach ($items as $item){
            $data = $item->toArray();
            $user_id = $item->user_id;
            $applet_id = $item->applet_id;
            $checkKey = $applet_id.'_'.$user_id;
            if(!empty($userData[$checkKey])){
                $data['recharge_number'] = $userData[$checkKey];
            }else{
                $data['recharge_number'] = 0;
            }
            if(!empty($userTime[$checkKey])){
                $data['dyeing_time'] = $userTime[$checkKey];
            }else{
                $data['dyeing_time'] = '';
            }
            //查询用户是否首次充值
//            $data['recharge_number'] = Payment::query()->where('status',2)->where('user_id',$item->user_id)->count('id');
//            $data['dyeing_time'] = Db::table('data_user_' . $item->applet_id)->where(['id' => $item->user_id])->value('dyeing_time');
            $data['status_name'] = Payment::$payMentStatus[$item->status] ?? '';
            $data['pay_type_name'] = Payment::$payType[$item->pay_type] ?? '';
            $data['user_platform_name'] = Payment::$userPlatform[$item->user_platform] ?? '';
            $data['amount'] = sprintf("%.2f",$data['amount']/100);
            $selectData[] =$data;

        }
        $data = $models->toArray();
        $data['data'] = $selectData;
        return $data;
    }


    public function backhaul($id){

        //$paymentInfo = Payment::query()->where(['id' => $id])->first();
        $paymentInfo = Payment::query()->where(['id' => $id,'is_backhaul' => 'N'])->first();
        if(!empty($paymentInfo)){
            Db::beginTransaction();
            try {
                $userInfo = Db::table('data_user_' . $paymentInfo->applet_id)->where(['id' => $paymentInfo->user_id])->first();
                //查找这个用户的userInfo
                if(!empty($userInfo)){
                    $spreadInfo = DataSpread::query()->where(['id' => $paymentInfo->spread_id])->first();
                    if (!empty($spreadInfo)) {

                        $user_type = $spreadInfo->user_type;
                        //判断星图的平台 20240116的新增逻辑
                        $spread_platform = $spreadInfo->spread_platform_id;
                        $backhaulsettingInfo = DataBackhaulSetting::query()->where(['id' => $spreadInfo->backhaul_setting_id])->first();
                        if (!empty($backhaulsettingInfo)) {
                            $backhaul_dimension = $backhaulsettingInfo->backhaul_dimension;
                            //普通用户
                            if($spread_platform == 1){
                                //抖音的单
                                if($paymentInfo->type == 2){

                                    if(!empty($userInfo->click_id)){

                                        $uploadData = $this->uploadPaymentDy($userInfo,$paymentInfo,$spreadInfo);
                                        if($uploadData){
                                            $this->installRel($userInfo,$paymentInfo,$backhaulsettingInfo,11);
                                            $paymentInfo->is_handle = 'Y';
                                            $paymentInfo->is_backhaul = 'Y';
                                            $paymentInfo->save();
                                            Db::commit();
                                            return $this->response(SystemCode::SYSTEM_SUCCESS,'回传成功');
                                        }
                                    }else{
                                        Db::rollBack();
                                        return $this->response(SystemCode::SYSTEM_ERROR,'用户没有对应的click_id');
                                    }

                                }else{

                                    //2为按照推广链接维度,1为计划维度
                                    if($backhaul_dimension == 1){
                                        if(empty($paymentInfo->ad_id) && empty($userInfo->ad_id)){
                                            Db::rollBack();
                                            return $this->response(SystemCode::SYSTEM_ERROR,'订单和用户都没有计划ID，回传失败');
                                        }
                                        if(!empty($userInfo->clue_token) && !empty($userInfo->ad_id) ){

                                            $uploadData = $this->uploadPayment($userInfo,$paymentInfo,$spreadInfo);
                                            if($uploadData){
                                                $this->installRel($userInfo,$paymentInfo,$backhaulsettingInfo,11);
                                                $paymentInfo->is_handle = 'Y';
                                                $paymentInfo->is_backhaul = 'Y';
                                                $paymentInfo->save();
                                                Db::commit();
                                                return $this->response(SystemCode::SYSTEM_SUCCESS,'回传成功');
                                            }else{
                                                Db::rollBack();
                                                return $this->response(SystemCode::SYSTEM_ERROR,'用户上报失败');
                                            }
                                        }else{
                                            Db::rollBack();
                                            return $this->response(SystemCode::SYSTEM_ERROR,'用户没有对应的回传token,ad_id');
                                        }
                                    }else{
                                        if(!empty($userInfo->clue_token)){
                                            $uploadData = $this->uploadPayment($userInfo,$paymentInfo,$spreadInfo);
                                            if($uploadData){
                                                $this->installRel($userInfo,$paymentInfo,$backhaulsettingInfo,11);
                                                $paymentInfo->is_handle = 'Y';
                                                $paymentInfo->is_backhaul = 'Y';
                                                $paymentInfo->save();
                                                Db::commit();
                                                return $this->response(SystemCode::SYSTEM_SUCCESS,'回传成功');
                                            }else{
                                                Db::rollBack();
                                                return $this->response(SystemCode::SYSTEM_ERROR,'用户上报失败');
                                            }
                                        }else{
                                            Db::rollBack();
                                            return $this->response(SystemCode::SYSTEM_ERROR,'用户没有对应的回传token');
                                        }
                                    }
                                }
                            //星图用户
                            }else if($spread_platform == 2){

                                if(!empty($userInfo->click_id)){

                                    $uploadData = $this->uploadPayment($userInfo,$paymentInfo,$spreadInfo);
                                    if($uploadData){
                                        $this->installRel($userInfo,$paymentInfo,$backhaulsettingInfo,11);
                                        $paymentInfo->is_handle = 'Y';
                                        $paymentInfo->is_backhaul = 'Y';
                                        $paymentInfo->save();
                                        Db::commit();
                                        return $this->response(SystemCode::SYSTEM_SUCCESS,'回传成功');
                                    }
                                }else{
                                    Db::rollBack();
                                    return $this->response(SystemCode::SYSTEM_ERROR,'用户没有对应的click_id');
                                }
                            }

                        }else{
                            Db::rollBack();
                            return $this->response(SystemCode::SYSTEM_ERROR,'推广链接不存在对应的回传配置');
                        }
                    }else{
                        Db::rollBack();
                        return $this->response(SystemCode::SYSTEM_ERROR,'订单不存在推广链接ID');
                    }
                }else{
                    Db::rollBack();
                    return $this->response(SystemCode::SYSTEM_ERROR,'订单不存在用户');
                }

            }catch (\Exception $e){
                Db::rollBack();
                return $this->response(SystemCode::SYSTEM_ERROR,$e->getLine() . '|' . $e->getMessage());
            }
        }else{
            return $this->response(SystemCode::SYSTEM_ERROR,'数据不存在,或已回传');
        }
    }

    public function backhaulInfo(int $payment_id){

        $backaulType= [
            '1' => '全量上报',
            '2'=> '订单金额不够回传',
            '3' => '订单保护回传',
            '4'=> '自定义上报漏单',
            '5'=> '自定义上报回传用户在关注当天自然日的所有充值',
            '6'=> '自定义上报回传用户在关注后24小时内的所有充值',
            '7'=> '自定义上报回传用户在关注当天自然日的所有首充',
            '8'=> '自定义上报回传用户在关注后24小时内的所有首充',
            '9'=> '订单不是首充，不回传',
            '10'=> '每几单漏几单都为0，此订单不回传',
            '11'=> '手动上报',
            '12'=>  '每几单漏0单',
            '13'=>  '用户染色时间已经超过设置上报时间',
        ];
        $backhaulDimension = [
            '1' => '计划ID维度',
            '2' => '推广链接维度'
        ];

       $backhaulInfo = DataPaymentBackhaul::query()->where('payment_id',$payment_id)->select(['backhaul_setting_id','type','execution_num','backhaul_dimension'])->orderBy('id','desc')->first();
        $returnData = array();
        if(!empty($backhaulInfo)){

            $settingInfo = DataBackhaulSetting::query()->where(['id' => $backhaulInfo->backhaul_setting_id])->first();
            $type = $backhaulInfo->type;
            $returnData['status'] = 1;
            $returnData['type'] = $type;
            $returnData['code'] = 200;
//            $returnData['type_name'] = $backaulType[$type];
//            $returnData['report_type'] = $settingInfo->report_type;
            $returnData['minimun_report_amount'] = $settingInfo->minimun_report_amount;
            $returnData['backhaul_filterate_num'] = $settingInfo->backhaul_filterate_num;
            $returnData['backhaul_filterate_miss'] = $settingInfo->backhaul_filterate_miss;
            $returnData['start_protect'] = $settingInfo->start_protect;
            $returnData['backhaul_dimension_name'] = $backhaulDimension[$backhaulInfo->backhaul_dimension];
            $returnData['info'] =  $backaulType[$type];
            if(in_array($type,[3,4,5,6,7,8])) {
                $returnData['info'] = $backaulType[$type] . ':第' . $backhaulInfo->execution_num . '单';
            }

        }else{
            $errorInfo = DataPaymentBackhaulError::query()->where(['payment_id' => $payment_id])->orderBy('id','desc')->first();

            if(!empty($errorInfo)){
                $returnData['status'] = 2;
                $returnData['code'] = 200;
                $returnData['info'] = $errorInfo->errorMsg;
            }
        }
        if(!empty($returnData)){
            return $this->response(SystemCode::SYSTEM_SUCCESS,'请求成功',$returnData);
        }else{
            return $this->response(SystemCode::SYSTEM_ERROR,'没有对应的回传信息');
        }


    }


    public function batchBackhaul(Array $params){

        $ids = $params['ids'];
        $paymentData = Payment::query()->whereIn('id', $ids)->where(['is_backhaul' => 'N'])->get();
        if(!empty($paymentData)){
            $errorMeg = [];
            $uploadAllData = [];
            foreach ($paymentData as $paymentDatum){
                $userInfo = Db::table('data_user_' . $paymentDatum->applet_id)->where(['id' => $paymentDatum->user_id])->first();
                if(!empty($userInfo)) {
                    $spreadInfo = DataSpread::query()->where(['id' => $paymentDatum->spread_id])->first();
                    if (!empty($spreadInfo)) {
                        $backhaulsettingInfo = DataBackhaulSetting::query()->where(['id' => $spreadInfo->backhaul_setting_id])->first();
                        if (!empty($backhaulsettingInfo)) {
                            $backhaul_dimension = $backhaulsettingInfo->backhaul_dimension;
                            $user_type = $spreadInfo->user_type;
                            //判断星图的平台 20240116的新增逻辑
                            $spread_platform = $spreadInfo->spread_platform_id;

                            if($spread_platform == 1){

                                if($paymentDatum->type == 2){
                                    if (!empty($userInfo->click_id)) {
                                        $uploadData['paymentInfo'] = $paymentDatum;
                                        $uploadData['userInfo'] = $userInfo;
                                        $uploadData['spreadInfo'] = $spreadInfo;
                                        $uploadData['backhaulsettingInfo'] = $backhaulsettingInfo;
                                        $uploadAllData[] = $uploadData;
                                    }else{
                                        $errorMeg[] = '抖音订单ID：' . $paymentDatum->id . ',用户没有对应的click_id';
                                        continue;
                                    }

                                }else{

                                    if($backhaul_dimension == 1){
                                        if(empty($paymentInfo->ad_id) && empty($userInfo->ad_id)){
                                            $errorMeg[]  = '微信订单ID：'.$paymentDatum->id.',订单和用户都没有计划ID，回传失败';
                                            continue;
                                        }else {

                                            if (!empty($userInfo->clue_token) && !empty($userInfo->ad_id)) {
                                                $uploadData['paymentInfo'] = $paymentDatum;
                                                $uploadData['userInfo'] = $userInfo;
                                                $uploadData['spreadInfo'] = $spreadInfo;
                                                $uploadData['backhaulsettingInfo'] = $backhaulsettingInfo;
                                                $uploadAllData[] = $uploadData;
                                            } else {
                                                $errorMeg[] = '微信订单ID：' . $paymentDatum->id . ',用户没有对应的回传token,ad_id';
                                                continue;
                                            }
                                        }
                                    }else{
                                        if (!empty($userInfo->clue_token)) {
                                            $uploadData['paymentInfo'] = $paymentDatum;
                                            $uploadData['userInfo'] = $userInfo;
                                            $uploadData['spreadInfo'] = $spreadInfo;
                                            $uploadData['backhaulsettingInfo'] = $backhaulsettingInfo;
                                            $uploadAllData[] = $uploadData;
                                        } else {
                                            $errorMeg[] = '微信订单ID：' . $paymentDatum->id . ',用户没有对应的回传token,ad_id';
                                            continue;
                                        }
                                    }
                                }
                            //星图用户
                            }else if($spread_platform == 2){

                                if (!empty($userInfo->click_id)) {
                                    $uploadData['paymentInfo'] = $paymentDatum;
                                    $uploadData['userInfo'] = $userInfo;
                                    $uploadData['spreadInfo'] = $spreadInfo;
                                    $uploadData['backhaulsettingInfo'] = $backhaulsettingInfo;
                                    $uploadAllData[] = $uploadData;
                                }else{
                                    $errorMeg[] = '微信订单ID：' . $paymentDatum->id . ',用户没有对应的click_id';
                                    continue;
                                }
                            }
                        } else {
                            $errorMeg[] = '订单ID：' . $paymentDatum->id . ',推广链接不存在对应的回传配置';
                            continue;
                        }

                    }else{
                        $errorMeg[] = '订单ID：'.$paymentDatum->id.',订单不存在推广链接ID';
                        continue;
                    }
                }else{
                    $errorMeg[]  = $paymentDatum->id.'订单不存在用户';
                    continue;
                }
            }
//            if(!empty($errorMeg)){
//                return $this->response(SystemCode::SYSTEM_ERROR_BACKHAUL,'上报失败',$errorMeg);
//            }else{
                if(!empty($uploadAllData)) {

                    $successMeg = [];
                    foreach ($uploadAllData as $uploadInfo){
                        $userInfo = $uploadInfo['userInfo'];
                        $paymentInfo = $uploadInfo['paymentInfo'];
                        $spreadInfo = $uploadInfo['spreadInfo'];
                        $backhaulsettingInfo = $uploadInfo['backhaulsettingInfo'];

                        if($paymentInfo->type == 2){
                            $uploadData = $this->uploadPaymentDy($userInfo,$paymentInfo,$spreadInfo);
                        }else{
                            $uploadData = $this->uploadPayment($userInfo,$paymentInfo,$spreadInfo);
                        }
//                        $uploadData = true;
                        if($uploadData){
                            $successMeg[] = '订单ID：'.$paymentInfo->id.',上报成功';
                            $this->installRel($userInfo,$paymentInfo,$backhaulsettingInfo,11);
                            $paymentInfo->is_handle = 'Y';
                            $paymentInfo->is_backhaul = 'Y';
                            $paymentInfo->save();
                        }else{
                            $errorMeg[] = '订单ID：'.$paymentInfo->id.',上报失败';
                        }
                    }
                    if(!empty($successMeg)){

                        return $this->response(SystemCode::SYSTEM_SUCCESS,'上报成功',array_merge($successMeg,$errorMeg));
                    }else{
                        return $this->response(SystemCode::SYSTEM_ERROR_BACKHAUL,'上报失败,没有成功上报的用户',$errorMeg);
                    }
                }else{
                    return $this->response(SystemCode::SYSTEM_ERROR_BACKHAUL,'上报失败,没有可以上报的数据',$errorMeg);
                }
            //}
        }else{
            return $this->response(SystemCode::SYSTEM_ERROR,'数据不存在,或已回传');
        }
    }

    public function installRel($userInfo,$paymentInfo,$backhaulsettingInfo,$type=1,$redis_key='',$is_first=1){


        DataPaymentBackhaul::create([
            'user_id' => $userInfo->id,
            'applet_id' => $paymentInfo->applet_id,
            'payment_id' => $paymentInfo->id,
            'xc_open_id' => $userInfo->xc_open_id,
            'clue_token' => $userInfo->clue_token,
            'type' => $type,
            'backhaul_setting_id' => $backhaulsettingInfo->id,
            'reids_key' => $redis_key,
            'spread_id' => $paymentInfo->spread_id,
            'is_first' =>$is_first,
            'ad_id' => $userInfo->ad_id,
            'click_id' => $userInfo->click_id,
            'backhaul_dimension' =>$backhaulsettingInfo->backhaul_dimension
        ]);
    }

    public function uploadPayment($userInfo,$paymentInfo,$spreadInfo){

        $open_id = $userInfo->xc_open_id;
        $union_id = $userInfo->unionid;
        $clue_token = $userInfo->clue_token;
        $click_id = $userInfo->click_id;
        $spread_platform = $spreadInfo->spread_platform_id;
        try {

            if($spread_platform == 1){
                $params = [
                    "clue_token" => $clue_token,
                    "union_id"  => $union_id,
                    "open_id"  => $open_id,
                    "event_type"  => "2",
                    "props" => [
                        'pay_amount' => $paymentInfo->amount
                    ]
                ];
                $nonce = rand();
                $timestamp = time();
                $signature = $this->getSign($nonce,$timestamp);
                $linkUrl = self::$reportUrl.'?timestamp='.$timestamp.'&nonce='.$nonce.'&signature='.$signature;
                //开始上传
                $result  = $this->request($params, $linkUrl,'POST');
                if($result['status'] == 200 ){
                    return true;
                }
            }else if($spread_platform == 2){
                $params = [];
//                $params = [
//                    "callback" => $click_id,
//                    "event_type"  => "2",
//                    "props" => [
//                        'pay_amount' => $paymentInfo->amount
//                    ]
//                ];
                $str = '{"pay_amount":"'.$paymentInfo->amount.'"}';
                $linkUrl = self::$starReportUrl.'?callback='.$click_id.'&event_type=2&props='.urlencode($str);
                //开始上传
                //$result  = $this->request($params, $linkUrl,'POST');
                $result = $this->http_curl($linkUrl,'GET');

                if($result['code'] == 0 ){
                    return true;
                }
            }
            return false;
        }catch (\Exception $e){
            return false;
        }

    }
    public function uploadPaymentDy($userInfo,$paymentInfo,$spreadInfo){

        $click_id =$userInfo->click_id;
        try {
            $params = [
                "context" =>
                    ["ad" =>[
                        'callback' => $click_id
                    ],
                    ],
                "event_type"  => "active_pay",
                "props" => [
                    'pay_amount' => $paymentInfo->amount
                ],
                "timestamp" => time()*1000
            ];

            $linkUrl = self::$dyreportUrl;
            //开始上传
            $result  = $this->request($params, $linkUrl,'POST');
            if($result['code'] == 0 ){
                return true;
            }
        }catch (\Exception $e){
            return false;
        }
        return false;
    }

    public function getSign($nonce,$timestamp)
    {
        $token = self::$token;
        $collect = [$token, $nonce, $timestamp];
        //获取token
        usort($collect, 'strcmp');
        $signature = sha1(implode('', $collect));

        return $signature;
    }


    /**
     * 传入数组进行HTTP POST请求
     */
    function request(array $params, string $url,string $method,string $access_token = null)
    {
        $client   = new Client([
            'timeout' => 3
        ]);
        $headers       = ['Content-Type' => 'application/json'];
        if(!empty($access_token)){
            $headers['access-token'] = $access_token;
        }

        $requestParams = [
            'headers' => $headers,
        ];
        if ($method == 'GET') {
            $requestParams['query'] = $params;
        } else {
            $requestParams['json'] = $params;//json_encode($params,JSON_UNESCAPED_UNICODE);
        }
        $response = $client->request($method,$url, $requestParams);
        if ($response->getStatusCode() !== 200) {
            return '';
        }
        $result   = $response->getBody()->getContents();
        $resultArr = json_decode($result,true);
        return $resultArr;

    }

    public function http_curl($url,$type='get',$res='json',$arr='')
    {
        //1.初始化curl
        $ch = curl_init();
        //2.设置curl的参数
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        if ($type == 'post') {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $arr);
        }
        //3.采集
        $output = curl_exec($ch);

        //如果返回的值，是json格式，则转换成数组
        if ($res == 'json') {
            if (curl_errno($ch)) {
                //请求失败，返回错误信息
                $reutrn = curl_error($ch);
                curl_close($ch);
                return $reutrn;

            } else {
                $reutrn = json_decode($output, true);
                curl_close($ch);
                //请求成功
                return $reutrn;
            }
        }
    }
}